/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 车辆叫号系统-物流中心审核
 */
import React, { useRef, useCallback, useEffect, useState } from 'react';
import {
  getRegisterQrcode,
  vehicleCallRegisterList,
  vehicleCallRegisterExamine,
} from '@/services/vehicleCall/register';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm, Space, Row, Col } from 'antd';
import { ProFormText, ModalForm } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import { useSelector } from 'umi';
import KbImage from '@/components/KbImage';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { TableListItem } from '@/pages/vehicleCall/register/index.d';
import { vehicleCall } from '../config';
import styles from './table.less';

interface BlackListTableType {
  activeKey: string;
  type: string;
}

interface RefuseModalProps {
  children: JSX.Element;
  tableRef: ActionType | undefined;
  item: TableListItem;
  activeKey: string;
}

const RefuseModal: React.FC<RefuseModalProps> = ({ item, children, tableRef, activeKey }) => {
  const [status, setStatus] = useState<string>('');
  const { mobile, name, logistics_center_name, address, contact_mobile } = item;
  return (
    <ModalForm
      title='物流中心审核'
      trigger={children}
      width={540}
      onFinish={async () => {
        const params = {
          status,
          id: item.id,
        };
        const { code, msg } = await vehicleCallRegisterExamine(params);
        if (code == 0) {
          message.success(msg);
          tableRef?.reload();
          return true;
        }
        message.error(msg);
        return false;
      }}
      submitter={{
        render: (props) =>
          activeKey === 'reviewed'
            ? [
                <Popconfirm title='确定拒绝？' key='refuse' onConfirm={() => props.submit()}>
                  <Button type='primary' danger onClick={() => setStatus('2')}>
                    拒绝
                  </Button>
                </Popconfirm>,
                <Popconfirm title='确定通过？' key='pass' onConfirm={() => props.submit()}>
                  <Button type='primary' onClick={() => setStatus('1')}>
                    通过
                  </Button>
                </Popconfirm>,
              ]
            : null,
      }}
    >
      <Row>
        <Col span={8}>状态：</Col>
        <Col span={16}>{vehicleCall[activeKey].txt}</Col>
        <Col span={8}>手机号：</Col>
        <Col span={16}>{mobile}</Col>
        <Col span={8}>姓名：</Col>
        <Col span={16}>{name}</Col>
        <Col span={8}>物流中心名称：</Col>
        <Col span={16}>{logistics_center_name}</Col>
        <Col span={8}>物流中心地址：</Col>
        <Col span={16}>{address}</Col>
        <Col span={8}>联系电话：</Col>
        <Col span={16}>{contact_mobile}</Col>
      </Row>
    </ModalForm>
  );
};

const RegisterTable = ({ type, activeKey }: BlackListTableType) => {
  const actionRef = useRef<ActionType>();
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [qrCode, setQrCode] = useState<string>('');
  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      align: 'center',
      ellipsis: true,
      renderFormItem: () => {
        return (
          <ProFormText
            placeholder='请输入手机号'
            name='mobile'
            rules={[{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确手机号' }]}
          />
        );
      },
    },
    {
      title: '物流中心名称',
      dataIndex: 'logistics_center_name',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '物流中心地址',
      dataIndex: 'address',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '注册时间',
      dataIndex: 'create_time',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '审核时间',
      dataIndex: 'audit_time',
      hideInTable: activeKey !== 'pass' && activeKey !== 'refuse',
      align: 'center',
      search: false,
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'is_in_black',
      key: 'option1',
      valueType: 'option',
      width: winSize === 'xs' ? 80 : 130,
      fixed: 'right',
      render: (_, record) => {
        return (
          <RefuseModal
            key='refuse'
            item={record}
            tableRef={actionRef.current}
            activeKey={activeKey}
          >
            <a key='link'>详情</a>
          </RefuseModal>
        );
      },
    },
  ];

  const requestTableData = useCallback(
    async (values) => {
      const { current, pageSize, mobile } = values;
      const reqData: {
        page: number;
        page_num: number;
        mobile: string;
        status: string;
      } = {
        page: current,
        page_num: pageSize,
        mobile,
        status: vehicleCall[activeKey].status,
      };
      const { code, data, msg } = await vehicleCallRegisterList(reqData);
      if (code == 0) {
        const formatList = data?.list?.map((item: any) => ({
          ...item,
          address:
            item.logistics_center_province +
            item.logistics_center_city +
            item.logistics_center_disctrict +
            item.logistics_center_address,
        }));
        return { data: formatList };
      } else {
        message.error(msg);
      }
    },
    [type],
  );

  useEffect(() => {
    if (activeKey !== type) return;
    actionRef.current?.reload();
    getRegisterQrcode().then((res: any) => {
      const { code, data, msg } = res;
      if (code == 0) {
        setQrCode(data);
      } else {
        message.error(msg);
      }
    });
  }, [activeKey, type]);

  return (
    <>
      <ProTable<TableListItem>
        actionRef={actionRef}
        rowKey='id'
        className={styles.table}
        request={requestTableData}
        columns={columns}
        options={false}
        pagination={{
          pageSize: 20,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        scroll={{ x: 1200 }}
        search={{
          optionRender: (_, { form }) => {
            return [
              <Button
                key='phone'
                type='primary'
                onClick={() => {
                  form?.submit();
                }}
              >
                搜索
              </Button>,
              <Space key='share'>
                <KbImage width={30} height={30} src={qrCode} />
                邀请二维码
              </Space>,
            ];
          },
        }}
      />
    </>
  );
};

export default RegisterTable;
